﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using SGIMail.DAL;
using SGIMail.Models;
using System.Threading.Tasks;
using PagedList;

namespace SGIMail.WebClient.Controllers
{
    [Authorize]
    public class ContactsController : Controller
    {
        DbAccess dbAccess = new DbAccess();

        // GET: Contacts
        public async Task<ActionResult> Index(string sortOrder, string currentFilter, string searchString, int? page)
        {
            int pageSize = 10;
            int pageNumber = (page ?? 1);
            List<ContactViewModel> cvmList = new List<ContactViewModel>();
            List<ContactViewModel> toView = new List<ContactViewModel>();
            //var contactList = db.Contacts.ToList();
            List<Contact> contactList = await dbAccess.GetUserContacts();
            //var contactList = dbAccess.GetUserContactViewModel();

            ViewBag.CurrentSort = sortOrder;
            ViewBag.CompanyNameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";

            if (searchString != null)
            {
                page = 1;
            }

            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;

            if (!String.IsNullOrEmpty(searchString))
            {
                foreach (var item in contactList)
                {
                    if (item.Company == null)
                    {
                        item.Company = new Company();
                        item.Company.CompanyName = "";
                    }
                }

                contactList = (contactList.Where(x => x.Company.CompanyName.ToUpper().Contains(searchString.ToUpper())
                                       || x.Name.ToUpper().Contains(searchString.ToUpper()))).ToList();
            }

            foreach (var c in contactList)
            {
                ContactViewModel cvm = new ContactViewModel();
                cvm.Contact = new Contact();
                cvm.Contact.Company = new Company();

                cvm = await dbAccess.GetContactViewDetails(c.ContactId);
                cvm.Participation = dbAccess.GetContactParticipation(c.ContactId);

                if (dbAccess.ContactExists(c.ContactId))
                {
                    cvm.LastDateActive = dbAccess.LastDateActiveForContact(c.ContactId);
                }

                if (cvm.Contact.Company == null)
                {
                    cvm.Contact.Company = new Company();
                    cvm.Contact.Company.CompanyName = "";
                }

                cvmList.Add(cvm);
            }

            toView = cvmList;

            switch (sortOrder)
            {
                case "name_desc":
                    toView = (cvmList.OrderByDescending(x => x.Contact.Company.CompanyName)).ToList();
                    break;
                case "Date":
                    toView = (cvmList.OrderBy(x => x.LastDateActive)).ToList();
                    break;
                case "date_desc":
                    toView = (cvmList.OrderByDescending(x => x.LastDateActive)).ToList();
                    break;
                default:
                    toView = (cvmList.OrderBy(x => x.Contact.Company.CompanyName)).ToList();
                    break;
            }

            return View(toView.ToPagedList(pageNumber, pageSize));
        }

        // GET: Contacts/Details/5
        public async Task<ActionResult> Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            ContactViewModel cvm = new ContactViewModel();
            cvm.EventDetails = new List<EventDetails>();
            cvm = await dbAccess.GetContactViewDetails(id);
            cvm.Participation = dbAccess.GetContactParticipation(id);
            Session["id"] = id;

            return View(cvm);
        }

        // GET: Contacts/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Contacts/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "ContactId, Name, Email, Company, Phone")] Contact contact)
        {
            if (ModelState.IsValid)
            {
                await dbAccess.AddContact(contact);
                return RedirectToAction("Index");
            }

            return View(contact);
        }

        // GET: Contacts/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            Contact contact = dbAccess.FindContact(id);

            if (contact == null)
            {
                return HttpNotFound();
            }

            return View(contact);
        }

        // POST: Contacts/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit([Bind(Include = "ContactId, Name, Email, Company, Phone")] Contact contact)
        {
            if (ModelState.IsValid)
            {
                await dbAccess.AddContact(contact);
                return RedirectToAction("Index");
            }

            return View(contact);
        }

        // GET: Contacts/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            Contact contact = dbAccess.FindContact(id);

            if (contact == null)
            {
                return HttpNotFound();
            }
            return View(contact);
        }

        // POST: Contacts/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> DeleteConfirmed(int id)
        {
            Contact contact = dbAccess.FindContact(id);
            await dbAccess.DeleteContact(contact);

            return RedirectToAction("Index");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult GetActivityData()
        {
            int id = Convert.ToInt32(Session["id"]);
            IQueryable<EventStatsticsViewModel> data = dbAccess.GetEventStatisticsByContactId(id);

            return Json(data, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult GetThemeData()
        {
            int id = Convert.ToInt32(Session["id"]);
            IQueryable<EventStatsticsViewModel> data = dbAccess.GetEventStatisticsByTheme(id);

            return Json(data, JsonRequestBehavior.AllowGet);
        }
    }
}
